# _*_ coding:utf-8 _*_
# @Time  : 2022.07.19
# @Author: zizlee

# 对工作统计指标参数数据进行配置
from typing import Optional
from fastapi import APIRouter, Header, Body, Query
from pydantic import BaseModel, ValidationError, datetime_parse, conint, validator
from db import FAConnection
from hutool import security
from v1_all_api import constant
from v1_all_api.all_utils import datetime_utils
from v1_all_api.all_response import AllResponse

from global_constant import VARIETY

work_setting_api = APIRouter()


class UserVarietyItem(BaseModel):
    user_id: int
    variety_en: str
    start_date: Optional[datetime_parse.date]
    end_date: Optional[datetime_parse.date]

    @validator('variety_en')
    def validate_variety_en(cls, value):
        if value.upper() not in VARIETY.VARIETY_NAMES.keys():
            raise ValidationError('variety_en invalidated')
        return value


@work_setting_api.post('/userVariety/')  # 添加一个品种任务
async def create_user_variety(ruizy_token: str = Header(...), variety: UserVarietyItem = Body(...)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    start_date = variety.start_date.strftime('%Y%m%d') if variety.start_date else datetime_utils.today(f='%Y%m%d')
    end_date = variety.end_date.strftime('%Y%m%d') if variety.end_date else '20991231'
    variety_en = variety.variety_en.upper()
    # 查询有效期的数据是否存在
    db_conn = FAConnection()
    exist_sql = "SELECT id FROM work_user_variety WHERE end_date>=%s AND user_id=%s AND variety_en=%s;"
    exist_obj = db_conn.query(exist_sql, param=[start_date, variety.user_id, variety_en],
                              fetchone=True, keep_conn=True)[0]
    if exist_obj:
        sql = "UPDATE work_user_variety SET start_date=%s,end_date=%s WHERE id=%s;"
        prm = (start_date, end_date, exist_obj['id'])
    else:
        # 添加数据
        sql = "INSERT INTO work_user_variety (user_id,variety_en,start_date,end_date) VALUES (%s,%s,%s,%s);"
        prm = (variety.user_id, variety_en, start_date, end_date)
    _, success = db_conn.execute(sql, param=prm)
    return AllResponse.operate_successfully() if success else AllResponse.server_error()


@work_setting_api.get('/userVariety/')  # 查询品种
async def query_user_variety(ruizy_token: str = Header(...), user: int = Query(None, ge=0)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    user_id = user if user else person['uid']  # 没有传递user就查询自己的
    sql = """
        SELECT a.id,a.user_id,a.variety_en,a.start_date,a.end_date,b.admin_name FROM work_user_variety As a 
        INNER JOIN ruizy_user As b ON a.user_id=b.id 
        WHERE user_id=%s
    """
    db_conn = FAConnection()
    records = db_conn.query(sql, param=[user_id])
    today = datetime_utils.today(f='%Y%m%d')
    for v in records:
        v['variety_name'] = VARIETY.VARIETY_NAMES.get(v['variety_en'])
        v['active'] = str(v['end_date']) >= today
    return AllResponse.operate_successfully(data=records)


class ExtendItem(BaseModel):
    user_id: conint(ge=1)
    admin_name: str
    group_en: str
    is_leader: int
    start_date: datetime_parse.date
    end_date: datetime_parse.date

    @validator('group_en')
    def validate_group(cls, value):
        if value not in constant.WORK_GROUPS.keys():
            raise ValidationError('user Group error!')
        return value


@work_setting_api.post('/userExtend/')  # 添加用户拓展
async def create_user_extend(ruizy_token: str = Header(...), extend: ExtendItem = Body(...)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    start_date = extend.start_date.strftime('%Y%m%d')
    end_date = extend.end_date.strftime('%Y%m%d')
    # 查询有效期的数据是否存在
    db_conn = FAConnection()
    exist_sql = "SELECT id FROM work_user_extend WHERE end_date>=%s AND user_id=%s;"
    exist_obj = db_conn.query(exist_sql, param=[start_date, extend.user_id], fetchone=True, keep_conn=True)[0]
    if exist_obj:  # 更新
        sql = "UPDATE work_user_extend SET group_en=%s,is_leader=%s,start_date=%s,end_date=%s WHERE id=%s;"
        prm = (extend.group_en, extend.is_leader, start_date, end_date, exist_obj['id'])
    else:  # 插入一条新的
        sql = """
            INSERT INTO work_user_extend (user_id,admin_name,group_en,is_leader,start_date,end_date) 
            VALUES (%s,%s,%s,%s,%s,%s);
        """
        prm = (extend.user_id, extend.admin_name, extend.group_en, extend.is_leader, start_date, end_date)
    _, success = db_conn.execute(sql, param=prm)
    return AllResponse.operate_successfully() if success else AllResponse.server_error()


@work_setting_api.get('/userExtend/')  # 查询用户拓展
async def query_user_extend(ruizy_token: str = Header(...), group: str = Query(...), end: str = Query(...)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    end_date = datetime_utils.auth_datetime_string(end, f='%Y%m%d')
    if not end_date:
        end_date = datetime_utils.today()
    sql = """
        SELECT id,user_id,admin_name,group_en,is_leader,start_date,end_date FROM work_user_extend 
        WHERE group_en=%s AND end_date>=%s;
    """
    db_conn = FAConnection()
    records = db_conn.query(sql, param=[group, end_date])
    for r in records:
        r['group_name'] = constant.WORK_GROUPS.get(r['group_en'])
    records.sort(key=lambda x: x['is_leader'], reverse=True)
    return AllResponse.operate_successfully(data=records)


class WorkVarietyItem(BaseModel):
    name: str
    expire: datetime_parse.date
    workload_short_message: float
    workload_strategy: float
    workload_investment_plan: float
    workload_lecture: float
    workload_article: float


@work_setting_api.post('/variety/')  # 添加工作模块使用的品种
def create_work_variety(ruizy_token: str = Header(...), variety: WorkVarietyItem = Body(...)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    db_conn = FAConnection()
    # 查询操作者
    op_user = db_conn.query("SELECT id,admin_name FROM ruizy_user WHERE id=%s LIMIT 1;", param=[person['uid']],
                            keep_conn=True, fetchone=True)[0]
    if not op_user:
        db_conn.close()
        return AllResponse.validate_error(msg='您的账号无效,无法操作！')
    # 查询有效期内是否存在
    expire_int = variety.expire.strftime('%Y%m%d')
    exist = db_conn.query("SELECT id FROM work_variety WHERE expire<=%s AND name=%s LIMIT 1;",
                          param=[expire_int, variety.name], keep_conn=True, fetchone=True)[0]
    if exist:
        db_conn.close()
        return AllResponse.validate_error(msg='品种已存在，确实需要添加，先修改原品种有效期！')
    # 添加
    sql = """
        INSERT INTO work_variety (name,expire,creator,workload_short_message,workload_strategy,workload_investment_plan,
        workload_lecture,workload_article) VALUES (%s,%s,%s,%s,%s,%s,%s,%s);
    """
    prm = (variety.name, variety.expire.strftime('%Y%m%d'), op_user['admin_name'], variety.workload_short_message,
           variety.workload_strategy, variety.workload_investment_plan, variety.workload_lecture,
           variety.workload_article)
    success, _ = db_conn.insert(sql, param=prm)
    return AllResponse.create_successfully() if success else AllResponse.server_error()


class PutVarietyItem(WorkVarietyItem):
    vid: int


@work_setting_api.put('/variety/')  # 修改工作品种数据
def modify_work_variety(ruizy_token: str = Header(...), variety: PutVarietyItem = Body(...)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    db_conn = FAConnection()
    # 查询操作者
    op_user = db_conn.query("SELECT id,admin_name FROM ruizy_user WHERE id=%s LIMIT 1;", keep_conn=True, fetchone=True)[
        0]
    if not op_user:
        db_conn.close()
        return AllResponse.validate_error(msg='您的账号无效,无法操作！')
    # 修改
    sql = "UPDATE work_variety SET name=%s,workload=%s,expire=%s,creator=%s WHERE id=%s LIMIT 1;"
    _, success = db_conn.execute(sql, param=[variety.name, variety.workload, variety.expire.strftime('%Y%m%d'),
                                 op_user['admin_name'], variety.vid])
    return AllResponse.operate_successfully() if success else AllResponse.server_error()


@work_setting_api.get('/variety/')  # 查询工作品种数据
def get_work_variety():
    db_conn = FAConnection()
    records = db_conn.query("SELECT * FROM work_variety;")
    for v in records:
        v['create_time'] = v['create_time'].strftime('%Y%m%d %H:%M:%S')
    return AllResponse.operate_successfully(data=records)
